<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd()"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles" style="width: 100%">
              <!-- type:index会自动生成序号 -->
              <el-table-column label="序号" type="index" width="50" />
              <el-table-column prop="name" label="角色名称" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column width="300" label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="success">分配权限</el-button>
                  <el-button size="mini" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="hDel(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                background
                layout="total,prev,pager,next"
                :total="total"
                :page-size="pageParams.pagesize"
                :current-page.sync="currentPage"
                @current-change="hCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑角色' : '新增角色'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <el-form
          ref="roleForm"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog=false">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="hSubmit"
            >确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, deleteRole, addRole, updateRole } from '@/api/setting'
export default {
  name: '',
  data() {
    return {
      roles: [],
      total: 0,
      currentPage: 1, // 默认当前页为1
      pageParams: {
        page: 1,
        pagesize: 2
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      isEdit: false,
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    maxNum() {
      return Math.ceil(this.total / this.pageParams.pagesize)
    },
    isLastPageFulled: function() {
      return this.total % this.pageParams.pagesize === 0
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    async loadRoles() {
      try {
        const { data: res } = await getRoles(this.pageParams)
        console.log('角色列表', res.data)
        this.roles = res.data.rows
        this.total = res.data.total
        // 保存数据
      } catch (err) {
        console.log(err)
      }
    },
    hCurrentChange(curPage) {
      this.pageParams.page = curPage
      this.loadRoles()
    },
    async doDel(id) {
      try {
        const { data: res } = await deleteRole(id)
        console.log('删除角色', res)
        this.$message.success(res.message)
        if (this.roles.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch((err) => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async doAdd() {
      try {
        const { data: res } = await addRole(this.roleForm)
        console.log('新增角色', res.data)
        this.$message.success(res.message)
        this.showDialog = false
        // if(表格的最后一页是满) {
        //   想查看最新添加的数据，要跳到最大页码的下一页
        //  }
        if (this.isLastPageFulled) {
          this.pageParams.page = this.maxNum + 1
          this.total++
        } else {
          // 想查看最新添加的数据，要跳到最大页码
          this.pageParams.page = this.maxNum
        }
        this.currentPage = this.pageParams.page
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('新增失败')
      }
    },
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    hEdit({ id, name, description }) {
      this.isEdit = true
      this.roleForm = { id, name, description }
      this.showDialog = true
    },
    async doEdit() {
      try {
        const { data: res } = await updateRole(this.roleForm)
        console.log('更新角色', res.data)
        this.$message.success(res.message)
        this.showDialog = false
        this.loadRoles()
      } catch (err) {
        console.log('updateRole', err)
      }
    },
    hClose() {
      this.roleForm = { // 表单数据项
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    }
  }
}
</script>
<style lang='less'  scoped>
</style>
